from crispy_forms.layout import HTML, ButtonHolder, Div, Field, Layout, Submit, Row, Column
from django import forms
from django.forms.widgets import PasswordInput
from crispy_forms.helper import FormHelper

from accounts.models import Account
from accounts.tokens import VerifyToken

class RegistForm(forms.Form):
    username = forms.CharField(
        label='username',
        required=True,
        min_length=4,
        max_length=80,
    )

    email = forms.EmailField(
        label='email',
        required=True,
    )

    first_name = forms.CharField(
        label='first_name',
        required=True,
        min_length=1,
        max_length=80,
    )

    last_name = forms.CharField(
        label='last_name',
        required=True,
        min_length=1,
        max_length=80,
    )

    password = forms.CharField(
        label='passowrd',
        widget=forms.PasswordInput,
        required=True,
        min_length=8,
        max_length=80,
    )

    passwd_confirm = forms.CharField(
        label='passwd_confirm',
        widget=PasswordInput,
        required=True,
        min_length=8,
        max_length=80,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = "id-registForm"
        self.helper.form_method = 'post'
        self.helper.form_action = 'regist'
        self.helper.form_show_labels = False

        self.helper.layout = Layout(
            Div(
                HTML('<span><i class="icon icon-user"></i></span>'),
                css_class="form-icon"
            ),

            Field('username', css_class="form-control item",
                placeholder='usernmae'),
            Field('email', css_class="form-control item", 
                placeholder='Email'),
            Row(
                Column(
                    Field('first_name', css_class="form-control item",
                    placeholder='First Name'), 
                    css_class="form-group col-md-6 mb-0"),
                Column(
                    Field('last_name', css_class="form-control item",
                    placeholder='Last Name'), 
                    css_class="form-group col-md-6 mb-0"),
                css_class="form-row"
            ),
            Field('password', css_class="form-control item",
                placeholder='Password'),
            Field('passwd_confirm', css_class="form-control item",
                placeholder='Password Confirm'),

            ButtonHolder(
                Submit('submit', 'Regist', css_class="btn btn-block create-account")
            )
        )

    def clean_username(self):
        value = self.cleaned_data['username']
        if Account.objects.filter(username=value):
            raise forms.ValidationError('Username has been registed!', code='invalide')
        else:
            return value

    def clean_email(self):
        value = self.cleaned_data['email']
        if Account.objects.filter(email=value):
            raise forms.ValidationError('Email has been used!', code='invalid')
        else:
            return value

    def clean_password(self):
        value = self.cleaned_data['password']
        if value.isdigit():
            raise forms.ValidationError('Password must hava characters', code='invalid')
        else:
            return value

    def clean_passwd_confirm(self):
        value = self.cleaned_data['passwd_confirm']

        try:
            target = self.cleaned_data['password']
        except Exception as e:
           raise forms.ValidationError('Password is valid!', code='invalid')
        else:
            if value != target or target is None:
                raise forms.ValidationError('Passwords are not same!', code='invalid')
            else:
                return value

class LoginForm(forms.Form):
    username = forms.CharField(
        label='username',
        min_length=4,
        max_length=80,
        required=True
    )

    password = forms.CharField(
        label='password',
        widget=forms.PasswordInput,
        min_length=8,
        max_length=80,
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-loginForm'
        self.helper.form_method = 'post'
        self.helper.form_action = 'login'
        self.helper.form_show_labels = False

        self.helper.layout = Layout(
            Div(
                HTML('<span><i class="icon icon-user"></i></span>'),
                css_class="form-icon"
            ),

            Field('username', css_class="form-control item", 
                placeholder="username/email"),
            Field('password', css_class="form-control item", 
                placeholder="password"),
            
            ButtonHolder(
                Submit('submit', 'Login', css_class="btn btn-block create-account")
            ),
        )

    def clean_username(self):
        value = self.cleaned_data['username']

        if not Account.objects.filter(username=value) and \
        not Account.objects.filter(email=value):
            raise forms.ValidationError('No such username or Email!', code='invalid')
        else:
            return value

class ForgetpasswdForm(forms.Form):
    email = forms.EmailField(
        label='email',
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-forgetForm'
        self.helper.form_method = 'post'
        self.helper.form_action = 'forget_password'
        self.helper.form_show_labels = False

        self.helper.layout = Layout(
            Div(
                HTML('<span><i class="icon icon-user"></i></span>'),
                css_class="form-icon"
            ),

            Field('email', css_class="form-control item", placeholder='E-mail'),

            ButtonHolder(
                Submit('submit', 'Submit', css_class="btn btn-block create-account")
            )
        )

    def clean_email(self):
        value = self.cleaned_data['email']
        if not Account.objects.filter(email=value):
            raise forms.ValidationError('Email is not registed!', code='invalid')
        return value

class NewPasswordForm(forms.Form):
    email = forms.EmailField(
        label='email',
        required=True,
    )

    new_password = forms.CharField(
        label='new_password',
        widget=PasswordInput,
        min_length=8,
        max_length=80,
    )

    password_confirm = forms.CharField(
        label='password_confirm',
        widget=PasswordInput,
        min_length=8,
        max_length=80,
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-newpasswdForm'
        self.helper.form_method = 'post'
        self.helper.form_action = 'new_password'
        self.helper.form_show_labels = False

        self.helper.layout = Layout(
            Div(
                HTML('<span><i class="icon icon-user"></i></span>'),
                css_class="form-icon"
            ),
            Field('email', css_class='form-control item', placeholder='E-mail'),
            Field('new_password', css_class='form-control item', placeholder='New Password'),
            Field('password_confirm', css_class='form-control item', placeholder='Password Confirm'),

            ButtonHolder(
                Submit('submit', 'Submit', css_class="btn btn-block create-account")
            )
        )

    def clean_email(self):
        value = self.cleaned_data['email']
        if Account.objects.filter(email=value):
            account = Account.objects.get(email=value)
            if account.token != '':
                data = VerifyToken.token_decode(account.token)
                try:
                    if data['email'] != value:
                        raise forms.ValidationError('You input error email!', code='invalid')
                except Exception:
                    raise forms.ValidationError('You input error email!', code='invalid')
            else:
                raise forms.ValidationError('You input error email!', code='invalid')
        else:
            raise forms.ValidationError('You input error email!', code='invalid')

        return value

    def clean_password(self):
        value = self.cleaned_data['new_password']
        if value.isdigit():
            raise forms.ValidationError('Password must hava characters', code='invalid')
        else:
            return value

    def clean_passwd_confirm(self):
        value = self.cleaned_data['password_confirm']

        try:
            target = self.cleaned_data['new_password']
        except Exception as e:
           raise forms.ValidationError('Password is valid!', code='invalid')
        else:
            if value != target or target is None:
                raise forms.ValidationError('Passwords are not same!', code='invalid')
            else:
                return value
